package zgrjb.snbq.teach_platform.component;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import zgrjb.snbq.teach_platform.config.OSSConfig;
import zgrjb.snbq.teach_platform.util.IDUtil;
import zgrjb.snbq.teach_platform.util.JsonData;

import java.io.IOException;

@Component
public class OSSComponent {

    @Autowired
    private OSSConfig ossConfig;



    public JsonData uploadFile(MultipartFile file) {


        String bucketName = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //oss客户端构建
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        //获取文件原始名称 xxx.jpg
        String originalFilename = file.getOriginalFilename();

        //user/2022/12/12/sdsdwe/
        String folder = "";
        String extendsion = originalFilename.substring(originalFilename.lastIndexOf("."));

        Long id = (Long) IDUtil.geneSnowFlakeID();
        //在oss上的bucket创建文件夹
        String newFilename = folder+"/"+id+extendsion;

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFilename, file.getInputStream());
            String url = "https://"+bucketName+"."+endpoint+"/"+newFilename;
            if(putObjectResult!=null) return JsonData.buildSuccess(url);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return JsonData.buildError("文件上传失败");
    }


}
